package com.example.a1.fannong.ui.main;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import com.example.a1.fannong.R;
import com.example.a1.fannong.adapter.ShoppingCartAdapter;
import com.example.a1.fannong.core.app.BaseFragment;
import com.example.a1.fannong.model.ShoppingCarEntity;
import com.example.a1.fannong.ui.shoppingcart.PlaceOrderActivity;
import com.example.a1.fannong.view.MyActionBar;

import java.util.ArrayList;
import java.util.List;

import cn.personal.library.view.listview.OnLoadMoreListener;
import cn.personal.library.view.listview.OnPullRefreshListener;
import cn.personal.library.view.listview.PullRefreshView;
import cn.personal.library.viewinject.FindViewById;
import cn.personal.library.viewinject.OnClick;
import cn.personal.library.viewinject.ViewInjecter;

public class ShoppingCartFragment extends BaseFragment implements ShoppingCartAdapter.CheckInterface,ShoppingCartAdapter.ModifyCountInterface {

    @FindViewById(R.id.data_list)
    private PullRefreshView pullRefreshView;
    @FindViewById(R.id.top_bar)
    private MyActionBar myActionBar;
    @FindViewById(R.id.select_rb)
    private CheckBox mAllSelectCb;
    @FindViewById(R.id.hj_tv)
    private TextView mSpecsTv;
    @FindViewById(R.id.js_bt)
    private TextView mAccountTv;

    private ShoppingCartAdapter shoppingCartAdapter;
    private List<ShoppingCarEntity> list;

    private double totalPrice = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量
    private boolean flag = false;

    private SparseArray<Boolean> mSelectState = new SparseArray<>();//批量模式下，用来记录当前选中状态

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shoppingcart, container, false);
        ViewInjecter.inject(this, view);
        myActionBar.setRightTextOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag = !flag;
                if (flag) {
                    myActionBar.setRightText("完成");
                    mAccountTv.setText("删除");
                    shoppingCartAdapter.isShow(false);
                } else {
                    myActionBar.setRightText("编辑");
                    mAccountTv.setText("去结算");
                    shoppingCartAdapter.isShow(true);
                }
            }
        });
        init();
        initListener();
     //   pullRefreshView.startPullRefresh();
        return view;
    }

    private void init(){
        shoppingCartAdapter = new ShoppingCartAdapter(getContext(), getData());
        shoppingCartAdapter.setCheckInterface(this);
        shoppingCartAdapter.setModifyCountInterface(this);
        pullRefreshView.setAdapter(shoppingCartAdapter);

        for (int i = 0; i < list.size(); i++){
            mSelectState.put(i,list.get(i).isChoosed());
        }
    }
    private List<ShoppingCarEntity> getData() {
        list = new ArrayList<>();
        for (int i = 0;i < 6;i++){
            list.add(new ShoppingCarEntity(""+i,"农业有机物产品"+i,"500g","10.0"+i ,i,true));
        }
        return list;
    }

    @OnClick({R.id.select_rb,R.id.js_bt})
    public void onItemClick(View view) {
        switch (view.getId()) {
            case R.id.select_rb:
                if (list.size() != 0){
                    if (mAllSelectCb.isChecked()){
                        for (int i = 0;i < list.size();i++){
                            list.get(i).setChoosed(true);
                        }
                        shoppingCartAdapter.notifyDataSetChanged();
                    }else {
                        for (int i = 0;i<list.size();i++){
                            list.get(i).setChoosed(false);
                        }
                        shoppingCartAdapter.notifyDataSetChanged();
                    }
                    statistics();
                }
                break;
            case R.id.js_bt:
                if (flag){
                    AlertDialog alert = new AlertDialog.Builder(getContext()).create();
                    alert.setTitle("操作提示");
                    alert.setMessage("您确定要将这些商品从购物车中移除吗？");
                    alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {return;
                                }
                            });alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    for (int i = 0; i< list.size(); i++){
                                        Log.d("lili",i +""+ mSelectState.get(i)+"--"+list.size());
                                        if (mSelectState.get(i)){
                                            Log.d("lili--t-",i+"||" +list.get(i).getName());
                                            list.remove(i);
                                        }
                                    }
                                    shoppingCartAdapter.notifyDataSetChanged();
                                    statistics();
                                }
                            });
                    alert.show();
                }else {
                    PlaceOrderActivity.startActivity(getContext());
                }
                break;
        }
    }
    public static void startActivity(Context context) {
        Intent intent = new Intent(context, ShoppingCartFragment.class);
        context.startActivity(intent);
    }

    private void initListener() {
        pullRefreshView.setOnPullRefreshListener(new OnPullRefreshListener() {
            @Override
            public void onPullDownRefresh(PullRefreshView pullRefreshView) {

            }
        });
        pullRefreshView.setLoadMoreEnable(false);
        pullRefreshView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(PullRefreshView pullRefreshView) {

            }
        });

    }

    /**
     * 单选
     * @param position  元素位置
     * @param isChecked 元素选中与否
     */
    @Override
    public void checkGroup(int position, boolean isChecked) {
       list.get(position).setChoosed(isChecked);
        if (isAllCheck()) {
            mAllSelectCb.setChecked(true);
            mSelectState.put(position,true);
        } else {
            mAllSelectCb.setChecked(false);
            mSelectState.put(position,false);
        }
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }

    /**
     * 增加
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doIncrease(int position, View showCountView, boolean isChecked) {
        ShoppingCarEntity shoppingCarEntity = list.get(position);
        int currentCount = shoppingCarEntity.getCount();
        currentCount++;
        shoppingCarEntity.setCount(currentCount);
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }

    /**
     * 删减
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doDecrease(int position, View showCountView, boolean isChecked) {
        ShoppingCarEntity shoppingCarEntity = list.get(position);
        int currentCount = shoppingCarEntity.getCount();
        if (currentCount == 1) {
            return;
        }
        if (currentCount > 0){
            currentCount--;
            shoppingCarEntity.setCount(currentCount);
            shoppingCartAdapter.notifyDataSetChanged();
            statistics();
        }else {
            showToast("喂~不能在减了哦");
        }

    }

    /**
     * 删除
     * @param position
     */
    @Override
    public void childDelete(int position) {
        showToast("删除成功！");
        list.remove(position);
        mSelectState.remove(position);
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }
    /**
     * 统计操作
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
     * 3.给底部的textView进行数据填充
     */
    public void statistics() {
        totalCount = 0;
        totalPrice = 0.00;
        for (int i = 0; i < list.size(); i++) {
            ShoppingCarEntity shoppingCarEntity = list.get(i);
            if (shoppingCarEntity.isChoosed()) {
                totalCount++;
                totalPrice += Double.valueOf(shoppingCarEntity.getPrice()) * shoppingCarEntity.getCount();
            }
        }
        mSpecsTv.setText(totalPrice+"");
      //  tv_settlement.setText("结算(" + totalCount + ")");
    }

    /**
     * 遍历list集合
     * @return
     */
    private boolean isAllCheck() {
        for (ShoppingCarEntity car : list) {
            if (!car.isChoosed())
                return false;
        }
        return true;
    }
}
